package demo_0416.hw;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class BankManager {
    private List<Account> accounts;
    private String dataFilePath;
    private String reportFilePath;

    public BankManager(String dataFilePath, String reportFilePath) {
        this.dataFilePath = dataFilePath;
        this.reportFilePath = reportFilePath;
        this.accounts = new ArrayList<>();
        loadAccounts();
    }

    // 从文件中加载账户信息
    private void loadAccounts() {
        try (BufferedReader br = new BufferedReader(new FileReader(dataFilePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split("\\s+");
                int id = Integer.parseInt(parts[0]);
                String firstname = parts[1];
                String lastname = parts[2];
                double balance = Double.parseDouble(parts[3]);
                accounts.add(new Account(id, firstname, lastname, balance));
            }
        }   catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 将账户信息保存到文件
    public void saveAccounts() {
        try (PrintWriter pw = new PrintWriter(new FileWriter(dataFilePath))) {
            for (Account account : accounts) {
                pw.println(account.getId() + " " + account.getFirstName() + " " + account.getLastName() + " " + account.getBalance());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 显示所有账户信息
    public void displayAccounts() {
        for (Account account : accounts) {
            System.out.println(account.getId() + " " + account.getFirstName() + " " + account.getLastName() + " " + account.getBalance());
        }
    }

    // 更新指定ID的账户信息
    public void updateAccount(int id, String firstname, String lastname, double balance) {
        for (Account account : accounts) {
            if (account.getId() == id) {
                account.setFirstName(firstname);
                account.setLastName(lastname);
                account.setBalance(balance);
                break;
            }
        }
        saveAccounts();
    }

    // 添加一个新的账户
    public void addAccount(Account account) {
        accounts.add(account);
        saveAccounts();
    }

    // 删除指定ID的账户
    public void deleteAccount(int id) {
        accounts.removeIf(account -> account.getId() == id);
        saveAccounts();
    }

    // 生成报告并保存到文件
    public void generateReport() {
        try (PrintWriter pw = new PrintWriter(new FileWriter(reportFilePath))) {
            pw.println("ID\tFirst Name\tLast Name\tbalance");
            for (Account account : accounts) {
                pw.println(account.getId() + "\t" + account.getFirstName() + "\t" + account.getLastName() + "\t" + account.getBalance());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
